#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
#include<cmath>
#include<map>
#include<set>
#include<cstdio>
#include<algorithm>
#define debug(a) cout<<#a<<"="<<a<<endl;
using namespace std;
const int maxn=2e5+1000;
typedef long long LL;
typedef pair<LL,LL>P;
inline LL read(){LL x=0,f=1;char ch=getchar();	while (!isdigit(ch)){if (ch=='-') f=-1;ch=getchar();}while (isdigit(ch)){x=x*10+ch-48;ch=getchar();}
return x*f;}
vector<LL>g[maxn];
LL dep[maxn],num[maxn];
vector<P>q[maxn];
LL ans[maxn];
void dfs(LL u,LL fa){
     dep[u]=dep[fa]+1;
     for(auto i:q[u]) ans[i.second] = -num[i.first];
     num[dep[u]]++;
     for(LL i=0;i<g[u].size();i++){
        LL v=g[u][i];
        if(v==fa) continue;
        dfs(v,u);
     }
     for(auto i:q[u]) ans[i.second]+=num[i.first];
}
int main(void){
   cin.tie(0);std::ios::sync_with_stdio(false);
   LL n;cin>>n;
   for(LL i=2;i<=n;i++){
       LL fa;cin>>fa;
       g[i].push_back(fa);
       g[fa].push_back(i);
   }
   LL m;cin>>m;
   for(LL i=1;i<=m;i++){
       LL u,d;cin>>u>>d;
       q[u].push_back({d+1,i});
   }
   dfs(1,1);
   for(LL i=1;i<=m;i++){
       cout<<ans[i]<<"\n";
   }
   return 0;
}
